var game = new Phaser.Game(512, 640, Phaser.CANVAS, 'total', { preload: preload, create: create, update: update, render: render });

function preload() {

    game.load.tilemap('level', 'assets/level.json', null, Phaser.Tilemap.TILED_JSON);

    game.load.image('tiles-1', 'assets/tiles.png');
    game.load.image('background', 'assets/background_ok.png');
    game.load.image('bullet', 'assets/crevette4.png');
    game.load.image('logo', 'assets/logo.png');
	game.load.image('coin', 'assets/coin.png');

    game.load.spritesheet('dude', 'assets/dude.png', 32, 48);
    game.load.spritesheet('droid', 'assets/droid.png', 32, 32);
    game.load.spritesheet('kaboom', 'assets/explode2.png', 64, 64);

    game.load.audio('gameMusic', ['assets/gameSong.mp3','assets/gameSong.ogg']);
    game.load.audio('jump', [ 'assets/jump.wav' ]);
    game.load.audio('crevetteSpray', [ 'assets/crevetteSpray.wav']);
    game.load.audio('ultraCrevetteSpray', [ 'assets/ultraCrevetteSpray.wav']);
    game.load.audio('explosionSound', [ 'assets/explosion.wav' ]);
    game.load.audio('tir', [ 'assets/tir.wav' ]);
    game.load.audio('die', [ 'assets/die.wav' ]);
	game.load.audio('coinSound', [ 'assets/coin.wav']);
}

var map;
var layer;
var player;
var facing = 'left';
var jumpTimer = 0;
var cursors;
var jumpButton;
var bg;
var aliens;

var isJumping = false;
var isContinu = false;

// Sizes and positions
var mapWidth = 512;
var mapHeight = 640;
var startPositionX = 230;
var startPositionY = 430;

// Sounds
var music;
var jumpSound;
var explosionSound;
var crevetteSpraySound;
var ultraCrevetteSpraySound;
var tirSound;
var dieSound;
var coinSound;

// Groups
var explosions;
var coins;

// Scoring
var playerScore = 0;
var playerBest = 0;
var crevetteCount = 0;
var coinCount = 0;

var eventGeneration;



var modeTir = 0;

var crevetteSprayActive = false;

var imageBackground;

var crevetteSprayText;

var logo;

var gameStarted = false;
var eventStartGame;

var shareOnTwitterLink = "https://twitter.com/home?status=I%20just%20beat%20ZZZ%20flappy%20bublles%20at%20Space%20flappy%20shrimp%20bubble%20ninja%20blob%202048%20X-Alpha%20Turbo%20Edition%20!%20papelou.fr/LD29%20%23LD29";

var bullets;
var fireRate = 150;
var nextFire = 0;

var login = "";

function randomIntFromInterval(min,max) {
    return Math.floor(Math.random()*(max-min+1)+min);
}

function addAlien() {

    var rectangleX = player.x - 50;
    var rectangleY = player.y - 50;
    var rectangleWidth = player.x + 50;
    var rectangleHeight = player.y + 50;

    var x = randomIntFromInterval(16,mapWidth);
    var y = randomIntFromInterval(16,mapHeight);

    while (x > rectangleX && x < rectangleX + rectangleWidth && y > rectangleY && y < rectangleY + rectangleHeight) {
        x = randomIntFromInterval(16,mapWidth);
        y = randomIntFromInterval(16,mapHeight);
    }

    var alien = aliens.create(x, y, 'droid');
    alien.anchor.setTo(0.5, 0.5);
    alien.animations.add('fly', [ 0, 1, 2, 3 ], 10, true);
    alien.play('fly');
    alien.body.moves = false;
    //var xTween = randomIntFromInterval(16,mapWidth);
    //var yTween = randomIntFromInterval(16,mapHeight);

    //var tween = game.add.tween(alien).to( { x:xTween, y: yTween }, 2000, Phaser.Easing.Linear.None, true, 0, 1, true);

    //tween.onLoop.add(newTween, this);
	
	newTween(alien);
}

function newTween(alien) {

    var xTween = randomIntFromInterval(16,mapWidth);
    var yTween = randomIntFromInterval(16,mapHeight);
    var tween = game.add.tween(alien).to( { x:xTween, y: yTween }, 2000, Phaser.Easing.Linear.None, true, 0, 1, true);

    tween.onLoop.add(newTween, this);
}

function startGame() {

    logo.kill();

    aliens = game.add.group();
    aliens.enableBody = true;
    aliens.physicsBodyType = Phaser.Physics.ARCADE;

    player = game.add.sprite(startPositionX, startPositionY, 'dude');


    game.physics.enable(player, Phaser.Physics.ARCADE);

    //player.body.bounce.y = 0.2;
    player.body.collideWorldBounds = true;
    player.body.setSize(20, 32, 5, 16);

    player.animations.add('left', [0, 1, 2, 3], 10, true);
    player.animations.add('turn', [4], 20, true);
    player.animations.add('right', [5, 6, 7, 8], 10, true);

    game.camera.follow(player);

    //  Our bullet group
    bullets = game.add.group();
    bullets.enableBody = true;
    //bullets.physicsBodyType = Phaser.Physics.ARCADE;
    bullets.createMultiple(30, 'bullet', 0, false);
    bullets.setAll('anchor.x', 0.5);
    bullets.setAll('anchor.y', 0.5);
    bullets.setAll('outOfBoundsKill', true);
    bullets.setAll('checkWorldBounds', true);

	coins = game.add.group();
	coins.enableBody = true;
	coins.createMultiple(16, 'coin', 0, false);
	coins.setAll('anchor.x', 0.5);
    coins.setAll('anchor.y', 0.5);
	coins.setAll('outOfBoundsKill', true);
	coins.setAll('checkWorldBounds', true);
	
    //  An explosion pool
    explosions = game.add.group();
    explosions.createMultiple(30, 'kaboom');
    explosions.forEach(setupInvader, this);

    eventGeneration = game.time.events.loop(2000, callbackAddMonster, this);


	
	
    gameStarted = true;
}


function create() {



    game.physics.startSystem(Phaser.Physics.ARCADE);

    imageBackground = game.add.sprite(game.world.centerX, game.world.centerY, 'background');
    imageBackground.anchor.setTo(0.5, 0.5);

    bg = game.add.sprite(0,0);
    bg.width = mapWidth;
    bg.height = mapHeight;



    map = game.add.tilemap("level");

    map.addTilesetImage('tiles-1');
    map.setCollisionByExclusion([ 13, 14, 15, 16, 46, 47, 48, 49, 51 ]);

    layer = map.createLayer('Tile Layer 1');

    //  Un-comment this on to see the collision tiles
    // layer.debug     = true;

    layer.resizeWorld();

    game.physics.arcade.gravity.y = 650;



    cursors = game.input.keyboard.createCursorKeys();
    jumpButton = game.input.keyboard.addKey(Phaser.Keyboard.UP);

    music = game.add.audio('gameMusic');
    music.play('',0,1,true);

    jumpSound = game.add.audio('jump');
    explosionSound = game.add.audio('explosionSound');
    crevetteSpraySound = game.add.audio('crevetteSpray');
    ultraCrevetteSpraySound = game.add.audio('ultraCrevetteSpray');
    tirSound = game.add.audio('tir');
    dieSound = game.add.audio('die');
	coinSound = game.add.audio('coinSound');

    logo = game.add.sprite(0, 0, 'logo');
    logo.fixedToCamera = true;
    eventStartGame = game.input.onDown.addOnce(startGame, this);
}

function callbackAddMonster() {
    for (var i =0; i < 3; i++)
        addAlien();
}

function setupInvader (invader) {

    invader.anchor.x = 0.5;
    invader.anchor.y = 0.5;
    invader.animations.add('kaboom');

}

function bulletHitEnemy(alien, bullet) {
	var alienX = alien.body.x;
	var alienY = alien.body.y;
	
    bullet.kill();
    alien.kill();
    //  And create an explosion :)
    var explosion = explosions.getFirstExists(false);
    explosion.reset(alienX, alienY);
    explosion.play('kaboom', 30, false, true);
    explosionSound.play();
	
	// And a coin !
	var coin = coins.create(alienX, alienY, "coin");
    // The coin is fading out 2 sec after popped
    game.time.events.add(Phaser.Timer.SECOND * 2, fadePicture, coin);
    // And then is deleted
   //game.time.events.add(Phaser.Timer.SECOND * 4, killObject, coin);
	
	//var rotationX = randomIntFromInterval(0,mapWidth);
	//var rotationY = randomIntFromInterval(0,mapHeight);
	
	//coin.rotation = game.physics.arcade.moveToXY(coin, rotationX, rotationY,500);

}

function fadePicture() {
   if(this != null)
        var tween = game.add.tween(this).to( { alpha: 0 }, 2000, Phaser.Easing.Linear.None, true, 0, 1, true);
		tween.onLoop.add(killObject, this);
}

function killObject() {
    if(this != null)
        this.kill();
}

function bulletTouchLayer (bullet, layer) {
    bullet.kill();

//    var explosion = explosions.getFirstExists(false);
//    explosion.reset(bullet.body.x, bullet.body.y);
//    explosion.play('kaboom', 30, false, true);
}

function update() {

    if (!gameStarted) return;

	game.physics.arcade.collide(player, layer);
	game.physics.arcade.collide(coins, layer);

    game.physics.arcade.overlap(bullets, layer, bulletTouchLayer, null, this);
    game.physics.arcade.overlap(bullets, aliens, bulletHitEnemy, null, this);
	
    player.body.velocity.x = 0;

    if (cursors.left.isDown)
    {
        player.body.velocity.x = -250;

        if (facing != 'left')
        {
            player.animations.play('left');
            facing = 'left';
        }
    }
    else if (cursors.right.isDown)
    {
        player.body.velocity.x = 250;

        if (facing != 'right')
        {
            player.animations.play('right');
            facing = 'right';
        }
    }
    else
    {
        if (facing != 'idle')
        {
            player.animations.stop();

            if (facing == 'left')
            {
                player.frame = 0;
            }
            else
            {
                player.frame = 5;
            }

            facing = 'idle';
        }
    }
    
    if (jumpButton.isDown && player.body.onFloor() && game.time.now > jumpTimer)
    {
        player.body.velocity.y = -250;
        jumpTimer = game.time.now + 750;
    }

    if (jumpButton.isDown)
    {
        if (player.body.onFloor()) {
            isJumping = true;
            isContinu = true;
            game.time.events.add(150, updateCounter, this);
            player.body.velocity.y = -250;
            jumpSound.play();
        }
    }
    else {
        if (!player.body.onFloor()) {
         isContinu = false;
        }
    }

    if (game.input.activePointer.isDown)
    {
        //  Boom!
        fire();
    }

    game.physics.arcade.overlap(player, aliens, collisionHandler, null, this);
	game.physics.arcade.overlap(player, coins, playerHitCoin, null, this);
	
    if (crevetteSprayActive) {

    }

}

function playerHitCoin(player, coin) {
	coin.kill();
	coinSound.play();
	incrementScore();
}

function updateCounter() {
    if (isContinu) {
        player.body.velocity.y = -300;
        isContinu = false;
    }

    isJumping = false;

}

function changeModeTir(newModeTir) {
    if (modeTir != newModeTir) {

        modeTir = newModeTir;

        crevetteSprayActive = true;


        switch (modeTir) {
            case 1:
                crevetteSpraySound.play();
                //	Font style
                crevetteSprayText = game.add.text(game.world.centerX, game.world.centerY, "CREVETTE SPRAY !!!", {
                    font: "45px Arial",
                    fill: "Red",
                    align: 'center'
                });
                crevetteSprayText.anchor.setTo(0.5, 0.5);
                break;
            case 2:
                ultraCrevetteSpraySound.play();
                //	Font style
                crevetteSprayText = game.add.text(game.world.centerX, game.world.centerY, "ULTRA\nCREVETTE SPRAY !!!", {
                    font: "45px Arial",
                    fill: "Red",
                    align: 'center'
                });
                crevetteSprayText.anchor.setTo(0.5, 0.5);
                break;
        }

        game.time.events.add(2000, finCrevetteSpray, this);

    }
}

function finCrevetteSpray() {
    crevetteSprayActive = false;
    crevetteSprayText.setText("");
}

function incrementScore(score) {
    playerScore++;
    $("#score").text(playerScore);
	
	if (playerScore > playerBest) {
        playerBest = playerScore;
        $("#best").text(playerBest);
        $("#shareOnTwitter").attr("href", shareOnTwitterLink.replace("ZZZ", playerBest));
    }
	
    game.time.events.remove(eventGeneration);

    var tempsApparition = 1000;

    if (playerScore < 10) {
        tempsApparition = 1000;
    }
    else if (playerScore < 25) {
        tempsApparition = 900;
        fireRate = 125;

    }
    else if (playerScore < 50) {
        tempsApparition = 750;
        fireRate = 115;
    }
    else if (playerScore < 75) {
        tempsApparition = 500;
        fireRate = 100;
    }
    else if (playerScore < 100) {
        tempsApparition = 250;
        fireRate = 75;
        changeModeTir(1);
    }
    else if (playerScore < 200) {
        tempsApparition = 200;
        fireRate = 75;
    }
    else if (playerScore >= 200) {
        tempsApparition = 150;
        changeModeTir(2);
    }

    eventGeneration = game.time.events.loop(tempsApparition, callbackAddMonster, this);
}

function resetScore() {
    playerScore = 0;
    $("#score").text(playerScore);
}

function resetModeTir() {
    modeTir = 0;
}

function collisionHandler(player, alien) {
    dieSound.play();
    $.ajax({
        type: "POST",
        url: "ajax.php",
        async: false,
        context: document.body
    }).done(gestionBestScore);
    reinit();
}

function gestionBestScore(scoreServeur) {
    if (playerBest > scoreServeur) {
        login = prompt("YOU ARE THE NEW SHRIMP VO DAO MASTER !!\nEnter your name :", login);
        $.ajax({
            type: "POST",
            data: { login: login, points: playerBest },
            url: "ajax.php",
            async: false,
            context: document.body
        }).done(updateHighScore);
    }
}

function updateHighScore(){
    $("#highScore").html("<h1>The Shrimp Vo Dao Master is " + login + " with " + playerBest + " points !</h1>");
}

function reinit() {
    resetScore();

    aliens.forEach(function(item) {
        item.kill();
    });
	
	coins.forEach(function(item) {
        item.kill();
    });

    player.body.position.x = startPositionX;
    player.body.position.y = startPositionY;

    resetModeTir();
    resetFireRate();
}

function resetFireRate() {
    fireRate = 150;
}

function render () {

//     game.debug.text("is continu : " + isContinu, 32, 32);
//     game.debug.text("is isJumping : " + isJumping, 32, 64);
//    game.debug.text("is jumpButton.isDown : " + jumpButton.isDown, 32, 128);
    // game.debug.body(player);
    // game.debug.bodyInfo(player, 16, 24);

}

function incrementCrevetteCount() {

    switch (modeTir) {
        case 0: crevetteCount++; break;
        case 1: crevetteCount += 3; break;
        case 2: crevetteCount += 5; break;
    }

    $("#crevetteCount").text(crevetteCount);
}

function fire () {

    if (game.time.now > nextFire && bullets.countDead() > 0)
    {
        incrementCrevetteCount();

        nextFire = game.time.now + fireRate;

        tirSound.play();

        var bullet = bullets.getFirstExists(false);

        if (bullet) {
            bullet.reset(player.x + 20, player.y + 35);
            bullet.rotation = game.physics.arcade.moveToXY(bullet, game.input.activePointer.x,game.input.activePointer.y,900);

            if (modeTir == 1)
            {
                var bullet2 = bullets.getFirstExists(false);
                if (bullet2) {
                    bullet2.reset(player.x + 20, player.y + 35);
                    bullet2.rotation = game.physics.arcade.moveToXY(bullet2, game.input.activePointer.x + 50,game.input.activePointer.y + 50,700);
                }


                var bullet3 = bullets.getFirstExists(false);
                if (bullet3) {
                    bullet3.reset(player.x + 20, player.y + 35);
                    bullet3.rotation = game.physics.arcade.moveToXY(bullet3, game.input.activePointer.x - 50,game.input.activePointer.y -50, 700);
                }
            }

            if (modeTir == 2)
            {
                var bullet2 = bullets.getFirstExists(false);
                if (bullet2) {
                    bullet2.reset(player.x + 20, player.y + 35);
                    bullet2.rotation = game.physics.arcade.moveToXY(bullet2, game.input.activePointer.x + 50,game.input.activePointer.y + 50,700);
                }


                var bullet3 = bullets.getFirstExists(false);
                if (bullet3) {
                    bullet3.reset(player.x + 20, player.y + 35);
                    bullet3.rotation = game.physics.arcade.moveToXY(bullet3, game.input.activePointer.x - 50,game.input.activePointer.y -50, 700);
                }

                var bullet4 = bullets.getFirstExists(false);
                if (bullet4) {
                    bullet4.reset(player.x + 20, player.y + 35);
                    bullet4.rotation = game.physics.arcade.moveToXY(bullet4, game.input.activePointer.x + 150,game.input.activePointer.y + 150,700);
                }

                var bullet5 = bullets.getFirstExists(false);
                if (bullet5) {
                    bullet5.reset(player.x + 20, player.y + 35);
                    bullet5.rotation = game.physics.arcade.moveToXY(bullet5, game.input.activePointer.x - 150,game.input.activePointer.y -150, 700);
                }
            }
        }



        //bullet.rotation = game.physics.arcade.moveToPointer(bullet, 900, game.input.activePointer, 320);


       /* var bullet2 = bullets.getFirstExists(false);

        bullet2.reset(player.x + 20, player.y + 35);

        bullet2.rotation = game.physics.arcade.moveToPointer(bullet2, 1000, game.input.activePointer, 500);*/

    }

}